<!--
 * @Author: your name
 * @Date: 2021-07-12 17:21:45
 * @LastEditTime: 2021-08-16 16:52:16
 * @Description:
-->
<template>
  <el-breadcrumb class="app-breadcremb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <span v-if="item.redirect === 'noRedirect' || index == levelList.length - 1" class="no-redirect">{{ item.meta.title }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
</el-breadcrumb>
</template>

<script lang="ts">
import { onMounted, ref, watch } from 'vue'
import { compile } from 'path-to-regexp'
import { useRoute, useRouter } from 'vue-router'

export default {
  name: 'Breadcrumb',

  setup() {
    const levelList = ref([] as any)
    const route = useRoute()
    const router = useRouter()

    const isDashboard = (route:Object):Boolean => {
      const name:string = route && route.name
      if (!name) {
        return false
      }
      const isDashboard = name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
      return isDashboard
    }

    // 获取面包屑
    const getBreadcrumb = () => {
      // 只展示路由中设置了meta.title的元素；
      let matched = route.matched.filter((item) => item.meta && item.meta.title)
      const first = matched[0]

      if (!isDashboard(first)) {
        matched = [{ path: '/dashboard', meta: { title: 'Dashboard' }}].concat(matched)
      }

      levelList.value = matched.filter((item) => item.meta && item.meta.title)
    }

    const pathCompile = (path: string) => {
      const { params } = route
      const toPath = compile(path)
      return toPath(params)
    }

    const handleLink = (item: any) => {
      const { redirect, path } = item
      if (redirect) {
        router.push(redirect)
      }
      router.push(pathCompile(path))
    }

    onMounted(() => {
      getBreadcrumb()
    })

    watch(route, () => {
      getBreadcrumb()
    })

    return {
      levelList,
      handleLink
    }
  }
}
</script>

<style lang="scss" scoped>
.navbar .breadcrumb-container {
  display: inline-block;
  font-size: 14px;
  line-height: 56px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
